package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.DishDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entitry.Category;
import com.itheima.reggie.entitry.Dish;
import com.itheima.reggie.entitry.DishFlavor;
import com.itheima.reggie.entitry.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@RestController
@RequestMapping("/dish")
@Transactional
public class DishController {


    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    //菜品分页查询
    @GetMapping("/page")
    public R<Map> selectPage(int page, int pageSize, String name) {

        //使用分页对象
        Page<Dish> Ipage = new Page(page, pageSize);

        //调用条件构建器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);

        //使用分页方法
        Page<Dish> dishPage = dishService.page(Ipage, lqw);
        //获取分页方法中的total总数
        int pageTotal = (int) dishPage.getTotal();
        //获取分页查询中的数据
        List<Dish> records = dishPage.getRecords();

        //创建dishDto集合
        List<DishDto> dishDtos = new ArrayList<>();
        //创建map集合，存放响应数据
        Map map = new HashMap();
        //将total数据放入map
        map.put("total", pageTotal);

        //利用for循环遍历数据
        for (Dish record : records) {

            DishDto dishDto = new DishDto();
            //设置菜品分类名称
            dishDto.setCategoryName(categoryService.getById(record.getCategoryId()).getName());
            //调用方法将record的数据复制给dishDto
            BeanUtils.copyProperties(record, dishDto);
            //在集合中添加
            dishDtos.add(dishDto);
        }
        //在map中放入数据
        map.put("records", dishDtos);
        return R.success(map);
    }


    //通过id查询，用于修改界面的回显数据
    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable("id") String id) {

        //创建dishDto对象
        DishDto dishDto = new DishDto();
        //System.out.println("----------------------------" + id);

        //通过id找到菜品
        Dish dish = dishService.getById(id);

        //获取对应分类ID
        Long categoryId = dish.getCategoryId();
        //根据分类id获取分类对象
        Category category = categoryService.getById(categoryId);

        //判断分类对象是否为空
        if (category != null) {
            //将分类名称传递给dishDto
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
        }

        //条件构建器
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        //根据菜品id找到对应的口味，并存入dishDto
        dishDto.setFlavors(dishFlavorService.list(lqw));
        //将菜品对象数据复制给dishDto
        BeanUtils.copyProperties(dish, dishDto);

        return R.success(dishDto);
    }


    //更新菜品信息
    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto) {

        //首先更改菜品信息
        dishService.updateById(dishDto);

        redisTemplate.delete("category_" + dishDto.getCategoryId());


        //获取菜品ID
        Long dishId = dishDto.getId();

        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();

        lqw.eq(DishFlavor::getDishId, dishId);

//        List<DishFlavor> list = dishFlavorService.list(lqw);
//        for (DishFlavor dishFlavor : list) {
//            dishFlavorService.removeById(dishFlavor.getId());
//        }

        //根据菜品id，先删除之前的口味信息
        dishFlavorService.remove(lqw);

        //获取dishDto中新的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();


        //在数据库添加口味信息
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
            dishFlavorService.save(flavor);
        }

        return R.success("修改成功！");
    }



    //批量删除菜品（单个删除）
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {

        //根据id值，删除菜品
        for (Long id : ids) {
            Dish byId = dishService.getById(id);
            dishService.removeById(byId);
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId, id);

            //删除对应的口味数据
            dishFlavorService.remove(lqw);
        }
        return R.success("删除成功");
    }



    //更新菜品状态
    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {

        //根据ids，更改对应菜品的状态
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("修改成功！");
    }

    //通过菜品分类获取对应的菜品信息，用于修改分类信息回显
    @GetMapping("/list")
    public R<List<DishDto>> selectDishByCat(Long categoryId) {

        List<DishDto> listRedis = (List<DishDto>) redisTemplate.opsForValue().get("category_" + categoryId);

        if (listRedis==null) {
            LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
            lqw.eq(categoryId != null, Dish::getCategoryId, categoryId);

            //获取当前分类id下的所有菜品
            List<Dish> list = dishService.list(lqw);
            List<DishDto> dtoList = new ArrayList<>();
            //根据菜品查询所有口味
            for (Dish dish : list) {
                //将当前dish复制给dishDto
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                //获取当前dish的口味
                LambdaQueryWrapper<DishFlavor> lqwDish = new LambdaQueryWrapper<>();
                lqwDish.eq(DishFlavor::getDishId, dish.getId());

                //将口味信息放入dishDTO
                dishDto.setFlavors(dishFlavorService.list(lqwDish));

                //将dishDto放入集合
                dtoList.add(dishDto);
            }

            redisTemplate.opsForValue().set("category_" + categoryId,dtoList,60, TimeUnit.MINUTES);
            return R.success(dtoList);

        }

        return R.success(listRedis);
    }


    @PostMapping
    public R<String> insert(@RequestBody DishDto dishDto){

        redisTemplate.delete("category_" + dishDto.getCategoryId());

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto,dish);

        dishService.save(dish);

        Dish byId = dishService.getById(dish);

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {

            flavor.setDishId(byId.getId());
            dishFlavorService.save(flavor);

        }

        return R.success("添加成功！");
    }

}
